package com.yunpeng.aidevice.common.controllers;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yunpeng.aidevice.biz.service.IDeviceBizService;
import com.yunpeng.aidevice.biz.service.IMerchantBizService;
import com.yunpeng.aidevice.biz.service.IUserBizService;
import com.yunpeng.aidevice.common.constant.ConstantValues;
import com.yunpeng.aidevice.common.dto.save.DeviceSaveDTO;
import com.yunpeng.aidevice.common.enums.ResultCodeEnum;
import com.yunpeng.aidevice.common.vo.SimpleEntityVO;
import com.yunpeng.aidevice.common.vo.user.MerchantLoginUserVO;
import com.yunpeng.aidevice.dao.constant.DictionariesConstant;
import com.yunpeng.common.dto.Result;
import com.yunpeng.common.util.HttpUtil;
import com.yunpeng.common.util.Md5Utils;
import com.yunpeng.common.util.ParametersCheckUtil;
import com.yunpeng.common.util.YpFileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * JapanPadController
 *
 * @author : Moore(hemw)
 * @date : 2020-04-29
 */
@RestController
@RequestMapping("/api/japanpadapi")
public class JapanPadController {

    /**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(JapanPadController.class);
    @Resource
    private IDeviceBizService deviceBizService;

    @Resource
    private IMerchantBizService merchantBizService;

    @Resource
    private IUserBizService userBizService;

    @Value(value = "${face_img_check}")
    private String faceImgCheckUrl;

    /**
     * 设备更新信息
     *
     * @param requestParam
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "queryDeviceSoftVersion", method = RequestMethod.POST)
    public Result<JSONObject> queryDeviceSoftVersion(@RequestBody JSONObject requestParam) {
        ParametersCheckUtil.mapIsNotNullOrderEmpty(requestParam, "没有传递任何参数");
        String deviceId = requestParam.getString("deviceId");
        return deviceBizService.getDeviceUpdateInfo(deviceId);
    }

    /**
     * 设备上传信息
     *
     * @param servletRequest
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "uploadRecordPath")
    public JSONObject uploadRecordPath(@RequestPart(value = "faceImage", required = false) MultipartFile faceImage, HttpServletRequest servletRequest) {
        String personnelId = servletRequest.getParameter("personnelId");
        String deviceId = servletRequest.getParameter("deviceId");
        String time = servletRequest.getParameter("time");
        String temperature = servletRequest.getParameter("temperature");
        if (StringUtils.isBlank(temperature)) {
            temperature = "0";
        }
        //非记录设备，直接返回
        if (!deviceBizService.checkExistDeviceId(deviceId)) {
            JSONObject result = new JSONObject();
            result.put("code", "0000");
            result.put("msg", "通行记录上传成功");
            result.put("data", new JSONObject());
            return result;
        }
        //上传文件
        Result<String> fileUploadResult = doSaveFile(faceImage, "deviceRecord", deviceId);
        if (!fileUploadResult.isSuccess()) {
            JSONObject result = new JSONObject();
            result.put("code", "0105");
            result.put("msg", "faceImage 不能为空");
            result.put("data", new JSONObject());
            return result;
        }
        LocalDateTime ldt = LocalDateTime.parse(time, ConstantValues.DATE_FORMAT_L);
        if (deviceBizService.saveRecordResult(personnelId, deviceId, ldt, Double.parseDouble(temperature), fileUploadResult.getData())) {
            JSONObject result = new JSONObject();
            result.put("code", "0000");
            result.put("msg", "通行记录上传成功");
            result.put("data", new JSONObject());
            return result;
        }
        JSONObject result = new JSONObject();
        result.put("code", "0001");
        result.put("msg", "上传失败");
        result.put("data", new JSONObject());
        return result;
    }


    /**
     * 人脸照片验证有效性
     *
     * @param requestParam
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "faceImgCheck", method = RequestMethod.POST)
    public Result<Void> faceImgCheck(@RequestBody JSONObject requestParam) {
        ParametersCheckUtil.mapIsNotNullOrderEmpty(requestParam, "没有传递任何参数");
        String imgUrl = requestParam.getString("imgUrl");
        ParametersCheckUtil.isNotNull(imgUrl, "照片为空");
        JSONObject param = new JSONObject();
        param.put("faceUrl", imgUrl);
        String response = HttpUtil.postData(faceImgCheckUrl, param.toJSONString(), HttpUtil.CONTENT_TYPE_JSON);
        if (StringUtils.isBlank(response)) {
            return Result.fail(ResultCodeEnum.PARAMETER_CHECK_FAILED);
        }
        JSONObject responseJson = JSON.parseObject(response);
        if (responseJson == null) {
            return Result.fail(ResultCodeEnum.PARAMETER_CHECK_FAILED);
        }
        if (200 != responseJson.getInteger("code")) {
            return Result.fail(ResultCodeEnum.PARAMETER_CHECK_FAILED);
        }
        if (responseJson.getInteger("data") > 70) {
            return Result.success();
        }
        return Result.fail(ResultCodeEnum.PARAMETER_CHECK_FAILED);
    }

    /**
     * 商户下拉菜单
     *
     * @return
     */
    @ResponseBody
    @CrossOrigin
    @RequestMapping(value = "dropDownMerchantList", method = RequestMethod.POST)
    public Result<List<SimpleEntityVO>> dropDownList(@RequestBody JSONObject requestParam) {
        ParametersCheckUtil.mapIsNotNullOrderEmpty(requestParam, "没有传递任何参数");
        String tenantCode = requestParam.getString("tenantCode");
        return merchantBizService.dropDownList(tenantCode);
    }

    /**
     * 新增设备
     *
     * @param deviceSaveDTO
     * @return
     */
    @ResponseBody
    @CrossOrigin
    @RequestMapping(value = "addNewDevice", method = RequestMethod.POST)
    public Result<Void> addNewDevice(@RequestBody DeviceSaveDTO deviceSaveDTO) {
        ParametersCheckUtil.isNotNull(deviceSaveDTO, "没有传递任何参数");
        ParametersCheckUtil.isNotNull(deviceSaveDTO.getDeviceNumber(), "需要传入设备编号");
        ParametersCheckUtil.isNotNull(deviceSaveDTO.getDeviceName(), "需要传入设备名称");
        ParametersCheckUtil.isNotNull(deviceSaveDTO.getDisabled(), "设备需要选择禁用或者启用");
        return deviceBizService.addNewDevice(deviceSaveDTO, DictionariesConstant.INSTANCE.getDefaultUserCode());
    }


    /**
     * 文件上传
     *
     * @param file
     * @param httpServletRequest
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "fileUpload", method = RequestMethod.POST)
    public Result<String> fileUpload(@RequestPart(value = "file", required = false) MultipartFile file, HttpServletRequest httpServletRequest) {
        String saveFor = httpServletRequest.getParameter("saveFor");
        String relationCode = httpServletRequest.getParameter("relationCode");
        ParametersCheckUtil.isNotNull(saveFor, "需要传入存储实体类型");
        ParametersCheckUtil.isNotNull(relationCode, "需要传入存储实体代码值");
        Result<String> fileUrl = doSaveFile(file, saveFor, relationCode);
        return fileUrl;
    }

    private Result<String> doSaveFile(MultipartFile file, String saveFor, String relationCode) {
        if (file == null) {
            return Result.fail(ResultCodeEnum.SAVE_DATA_FAILED);
        }
        String timeSuffix = ConstantValues.DAY_FORMAT_L.format(LocalDateTime.now());
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        int length = DictionariesConstant.INSTANCE.getFileAllowSuffix().toLowerCase().indexOf(suffix.toLowerCase());
        if (length == -1) {
            return Result.fail(ResultCodeEnum.SAVE_DATA_FAILED);
        }
        if (!ConstantValues.APK.equalsIgnoreCase(suffix)) {
            if (file.getSize() > DictionariesConstant.INSTANCE.getMaxFileSize()) {
                return Result.fail(ResultCodeEnum.SAVE_DATA_FAILED);
            }
        }
        String fileLocation = String.format("%s/%s/%s", saveFor, relationCode, timeSuffix);
        String fileName = Md5Utils.getMd5(UUID.randomUUID().toString()).substring(8, 24);
        String realFileName = String.format("%s.%s", fileName, suffix);
        String realFilePath = String.format("%s/%s", DictionariesConstant.INSTANCE.getFileSavePath(), fileLocation);
        try {
            if (YpFileUtils.saveFile(file.getInputStream(), realFileName, realFilePath)) {
                String fileUrl = String.format("%s/%s/%s", DictionariesConstant.INSTANCE.getFileAccessUrl(), fileLocation, realFileName);
                return Result.success(fileUrl);
            }
        } catch (IOException ex) {
            LOGGER.error("get file input steam error,", ex);
        }
        return Result.fail(ResultCodeEnum.SAVE_DATA_FAILED);
    }

    /**
     * 根据用户电话号码精确匹配商户信息(作为登录选择)
     *
     * @param requestParam
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getMerchantUserByPhone", method = RequestMethod.POST)
    public Result<List<MerchantLoginUserVO>> getMerchantUserByPhone(@RequestBody JSONObject requestParam) {
        ParametersCheckUtil.mapIsNotNullOrderEmpty(requestParam, "没有传递任何参数");
        String phone = requestParam.getString("phone");
        ParametersCheckUtil.isNotNull(phone, "需要传入用户电话");
        return userBizService.getMerchantUserByPhone(phone);
    }
}
